/* eslint-disable no-console */
const fs = require("fs");
const path = require("path");
const { app } = require("electron");

const logPath = app.getPath("logs");
const configPath = path.join(app.getPath("userData"), "config.json");

const log = {
  error: (data = "") => {
    try {
      if (typeof data !== "string") {
        return;
      }
      const date = new Date();
      const text =
        [date.getFullYear(), date.getMonth(), date.getDate()].join("-") +
        " " +
        [date.getHours(), date.getMinutes(), date.getSeconds()].join(":") +
        " ";
      fs.appendFile(
        path.join(logPath, "error.log"),
        text + data + "\n",
        () => {}
      );
    } catch (error) {
      console.error("log error:", error);
    }
  },
};

const getConfig = () => {
  try {
    const data = fs.readFileSync(configPath);
    return JSON.parse(data) || {};
  } catch (error) {
    log.error(JSON.stringify(error));
    return {};
  }
};

const setConfig = (data = {}) => {
  // console.log("configPath:", configPath);
  try {
    fs.writeFileSync(configPath, JSON.stringify(data));
  } catch (error) {
    log.error(JSON.stringify(error));
  }
};

module.exports = {
  log,
  getConfig,
  setConfig,
};
